package com.atguigu.consumer.demo.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;

import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ConsumerListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "SPRING-TEST-QUEUE")
            ,exchange = @Exchange(value = "SPRING-TEST-EXCHANGE",ignoreDeclarationExceptions = "true",type = ExchangeTypes.TOPIC)
            ,key = {"a.*"}))
    public void listener(String msg, Channel channel, Message message) throws IOException {
        try {
            System.out.println(msg);
            int i = 1/0;
            // 手动确认消息,是否批量确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
            // 是否已经重试过
            if (message.getMessageProperties().getRedelivered()){
                // 已重试过直接拒绝
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } else {
                // 未重试过，重新入队
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            }
        }
    }

    @RabbitListener(queues = {"SPRING-DEAD-QUEUE"})
    public void listener2(String msg, Channel channel, Message message) throws IOException {
        try {
            System.out.println(msg);
            int i = 1/0;
            // 手动确认消息,是否批量确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            // 是否已经重试过
            if (message.getMessageProperties().getRedelivered()){
                // 已重试过直接拒绝
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } else {
                // 未重试过，重新入队
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            }
        }
    }
}
